<template>
  <header>
    <div v-for="item in data" :key="item.id">
      name :{{ item.username }} <button @click="deleteDatabase(item.id)">删除数据</button>
    </div>
    <button @click="createDatabaseAndInsertData">创建数据库并插入数据</button>
    <!-- <img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />
    </div> -->
  </header>

  <main>
    <TheWelcome />
  </main>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import HelloWorld from "./components/HelloWorld.vue";
import TheWelcome from "./components/TheWelcome.vue";
import { useCrypto } from "../utils/crypto"
import { useDatabase } from "../utils/database"
// const sqlite3 = require("better-sqlite3");

const data = ref()
const { encryptText, decryptText } = useCrypto()
const { query, execute } = useDatabase()

function createDatabaseAndInsertData() {

  execute('INSERT INTO sample VALUES (?, ?)', [Date.now(), encryptText(generateRandomString(6))])
  data.value = query('SELECT * FROM sample');
  // // 插入两行模拟数据
  // const insertStmt = db.prepare('INSERT INTO sample VALUES (?, ?)');

  // insertStmt.run(Date.now(), encryptText(generateRandomString(6)));

  // console.log('数据库和数据插入完成。');
  // data.value = db.prepare('SELECT * FROM sample').all()

  // // 关闭数据库连接
  // db.close();
}

function deleteDatabase(id: number) {
  // const db = new sqlite3('db1.db');
  // // 删除 ID 为 1 的数据
  // const deleteStmt = db.prepare('DELETE FROM sample WHERE id = ?');
  // deleteStmt.run(id);
  // data.value = db.prepare('SELECT * FROM sample').all()
  // console.log(`ID 为 ${id} 的数据已删除。`);
  execute('DELETE FROM sample WHERE id = ?', [id])
  data.value = query('SELECT * FROM sample');
}

// 生成随机字符串
function generateRandomString(length: number): string {
  var randomBytes = new Uint8Array(length);
  window.crypto.getRandomValues(randomBytes);
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var charactersLength = characters.length;
  var result = '';
  for (var i = 0; i < length; i++) {
    var randomIndex = randomBytes[i] % charactersLength;
    result += characters.charAt(randomIndex);
  }
  return result;
}

onMounted(() => {
  // const db = new sqlite3('db1.db');
  // data.value = db.prepare('SELECT * FROM sample').all()
  // // 关闭数据库连接
  // db.close();
  data.value = query('SELECT * FROM sys_user');
  console.log(encryptText('admin'));
  
})
</script>

<style scoped>
header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>
../utils/crypto